import requests
import pika
from kafka import KafkaProducer
import json
import time

BASE = "http://localhost:8080"

def create_test_task():
    """创建一个测试任务，故意配置错误的参数来产生失败"""
    data = {
        "name": "test-error-task",
        "direction": "KAFKA_TO_RABBIT",
        "kafkaSourceBootstrap": "192.168.168.23:9092",
        "kafkaSourceTopic": "nonexistent_topic",  # 不存在的topic
        "kafkaSourceGroup": "test-error-group",
        "kafkaSourceOffsetReset": "latest",
        "rabbitTargetHost": "192.168.168.23",
        "rabbitTargetPort": 5672,
        "rabbitTargetVhost": "/",
        "rabbitTargetUsername": "guest",
        "rabbitTargetPassword": "guest",
        "rabbitTargetExchange": "",
        "rabbitTargetRoutingKey": "nonexistent_queue",  # 不存在的队列
        "enabled": True,
        "concurrency": 1,
        "maxRetries": 3,
        "retryBackoffMs": 1000
    }
    r = requests.post(BASE + "/api/tasks", json=data)
    r.raise_for_status()
    return r.json()

def send_test_message():
    """发送测试消息到Kafka"""
    try:
        producer = KafkaProducer(
            bootstrap_servers=['192.168.168.23:9092'],
            value_serializer=lambda x: json.dumps(x).encode('utf-8')
        )
        
        message = {"test": "message", "timestamp": time.time()}
        producer.send('test_topic', message)
        producer.flush()
        print("发送测试消息到 test_topic")
    except Exception as e:
        print(f"发送消息失败: {e}")

def create_rabbit_queue():
    """创建RabbitMQ测试队列"""
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='192.168.168.23', credentials=pika.PlainCredentials('guest', 'guest'))
        )
        channel = connection.channel()
        channel.queue_declare(queue='test_queue', durable=True)
        
        # 发送一些测试消息
        for i in range(5):
            message = f"Test message {i+1}"
            channel.basic_publish(exchange='', routing_key='test_queue', body=message)
        
        connection.close()
        print("创建了 test_queue 并发送了5条消息")
    except Exception as e:
        print(f"创建队列失败: {e}")

if __name__ == "__main__":
    print("创建测试数据...")
    
    # 创建队列和发送消息
    create_rabbit_queue()
    send_test_message()
    
    # 创建一个会失败的任务
    task = create_test_task()
    print(f"创建了测试任务: {task['id']}")
    
    # 启动任务（会失败）
    requests.post(f"{BASE}/api/tasks/{task['id']}/start")
    print("启动了任务，等待产生错误...")
    
    time.sleep(5)
    
    # 停止任务
    requests.post(f"{BASE}/api/tasks/{task['id']}/stop")
    print("停止了任务")
    
    print("测试数据创建完成！现在可以在界面上看到失败的任务了。")
